package com.chap14;

/**
 * <p>
 * <code>ReOrderTest</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-04-13 9:37
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class ReOrderTest1 {
    private static int x = 0,y=0;
    private static volatile int a = 0,b=0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        while (true){
            i++;
            x=0;
            y=0;
            a=0;
            b=0;
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    shortWait(20000);
                    a = 1; //volatile 写
                    x=b;//读b  volatile读
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
                    y=a;
                }
            });

            t1.start();
            t2.start();
            t1.join();
            t2.join();

            System.out.println("第"+i+"次（"+x+"，"+y+"）");

            if (x==0 && y ==0){
                break;
            }
        }
    }

    public static void shortWait(long interval){
        long start = System.nanoTime();
        long end;
        do {
            end = System.nanoTime();
        }while (start+interval>=end);
    }

}
